import service from '../../common/service';
import {type IResponseData, type IRequestData, type IRequest} from '../../types/public'
import dateRangUtil from '@/common/dateRangUtil';
import { useModuleDataStore } from '@/store/useModuleDataStore';
import { useMainStore } from '@/store/modules/store';
import { getRdsUrl } from "@/hooks/rdsServices";
interface DataStored {
	[key: string]: any;
}
// 获取数据的函数
const getStorageSync = (key: string): DataStored => {
	const res = uni.getStorageSync(key);
	return res ? JSON.parse(res) : undefined; // 使用类型断言返回一个空对象
};

const setStorageSync = (key: string, data: any): void => {
	// 转为json 字符串存储
	uni.setStorageSync(key, JSON.stringify(data));
};

const addlocalStorage = (key: String, value: any): void => {
	//这里是添加key和value也转换成json
	service.setStorageSync(key, value)
}

// 定义错误信息的接口
interface IErrorInfo {
	// 根据实际错误信息结构定义属性
	message?: string;
}

const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT") || null;
let MainURL = '',
	OAURL = '';
//console.log(CUSTOMEROBJECT);

if (CUSTOMEROBJECT && Object.keys(CUSTOMEROBJECT).length !== 0) {
	const {EnjoyMain, EnjoyRMIS, EnjoyOA} = CUSTOMEROBJECT;
	MainURL = EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : `${EnjoyMain.c_request_http_type}://${EnjoyMain.c_mobile_service_ip}/Enjoy/Service`
	OAURL = EnjoyOA.c_mobile_service_ip.indexOf('http') >= 0 ? '' : `${EnjoyOA.c_request_http_type}://${EnjoyOA.c_mobile_service_ip}/Enjoy/Service`
}


/**
 * 查询客户代码，固定是从昂捷云服务器获取
 */

const GetCloudCustDef = (req: IRequestData, resSuccess: (data: IResponseData) => void, resFail: (error: any) => void) => {

	// MARK: - DEBUGGER START
	// 调试切换到本地代理 http://localhost:5173/
	if (window?.location?.host?.indexOf("localhost") === 0) {
		const localData= {
			"ObjectData": {
				"RowsCount": 0,
				"PageCount": 0,
				"CurrentPage": 0,
				"PageSize": 0,
				"ErrorString": null,
				"ReturnObject": [
					{
						"c_cloud_id": "RDSCS",
						"c_application": "EnjoyBCM",
						"c_ismain_app": "否",
						"c_name": "RDS测试管易通",
						"c_status": "已启用",
						"c_modified_user": "陈涛",
						"c_modified_dt": "2024-04-30 15:29:49",
						"c_note": "",
						"c_mobile_service_ip": "localhost:5173",
						"c_request_http_type": "http",
						"c_is_hiddenid": "否"
					},
					{
						"c_cloud_id": "RDSCS",
						"c_application": "EnjoyOA",
						"c_ismain_app": "是",
						"c_name": "RDS测试管易通",
						"c_status": "已启用",
						"c_modified_user": "陈涛",
						"c_modified_dt": "2024-04-30 15:29:49",
						"c_note": "",
						"c_mobile_service_ip": "localhost:5173",
						"c_request_http_type": "http",
						"c_is_hiddenid": "否"
					},
					{
						"c_cloud_id": "RDSCS",
						"c_application": "EnjoyRDS",
						"c_ismain_app": "否",
						"c_name": "RDS测试管易通",
						"c_status": "已启用",
						"c_modified_user": "陈涛",
						"c_modified_dt": "2024-04-30 15:29:49",
						"c_note": "",
						"c_mobile_service_ip": "localhost:5173",
						"c_request_http_type": "http",
						"c_is_hiddenid": "否"
					},
					{
						"c_cloud_id": "RDSCS",
						"c_application": "EnjoyCRM",
						"c_ismain_app": "否",
						"c_name": "RDS测试管易通",
						"c_status": "已启用",
						"c_modified_user": "陈涛",
						"c_modified_dt": "2024-04-30 15:29:49",
						"c_note": "",
						"c_mobile_service_ip": "localhost:5173",
						"c_request_http_type": "http",
						"c_is_hiddenid": "否"
					}
				],
				"AggregateObject": null
			},
			"UniqueKey": null,
			"MethodName": null,
			"SourceMethodName": null,
			"Tag": null,
			"UserState": null,
			"Exception": null,
			"HasException": false
		};
		resSuccess(localData)
		return ;
	}

	// MARK: - DEBUGGER STOP
	let request = {
		url: `${service.cloudServiceAddress}/Enjoy/Service`,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				...req,
			},
			MethodName: "GetCloudCustDef",
		},
	};
	service.request<IResponseData>(request, (res) => {
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, (failinfo) => {
		let request1 = {
			url: `${service.cloudServiceAddressBak}/Enjoy/Service`,
			data: {
				UniqueKey: "管易通40公共",
				ObjectData: {
					...req, //由vue文件传值，
				},
				MethodName: "GetCloudCustDef",
			},
		};

		service.request<IResponseData>(request1, (res1) => {
			if (resSuccess && res1 && res1.data) {
				resSuccess(res1.data);
			}
		}, (failinfo2) => {
			let request2 = {
				url: `${service.cloudServiceAddressBak2}/Enjoy/Service`,
				data: {
					UniqueKey: "管易通40公共",
					ObjectData: {
						...req, //由vue文件传值，
					},
					MethodName: "GetCloudCustDef",
				},
			};

			service.request<IResponseData>(request2, (res2) => {
				if (resSuccess && res2 && res2.data) {
					resSuccess(res2.data);
				}
			}, resFail);
		});
	});
}

// 登录
const MobileLoginNew = (req: IRequestData, resSuccess: (data: IResponseData) => void, resFail: (error: any) => void) => {
	const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
		.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +
		'/Enjoy/Service';

	let request:RequestOptions = {
		url: URL,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				...req, //由vue文件传值，
			},
			MethodName: "MobileLoginNew",
		},
	}
	service.request(request, (res) => {
		if (resSuccess && res && res.data) {
			let retLogin = res.data;
			resSuccess(retLogin);
			if(retLogin && !retLogin.HasException && retLogin.ObjectData && retLogin.ObjectData.bLogin == true && retLogin.ObjectData.sIsInitPwd!='是'){
				setTimeout(() => {
					FetchAvailablePortalData();
				}, 1300);
			}
		} else {
			// resFail(res.data)
			console.log('==========失败============');
		}
	}, resFail);
}
//退出登录
const MBMLogOut = (req: IRequestData, resSuccess: (data: IResponseData) => void, resFail: (error: any) => void) => {

	const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
			.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +
		'/Enjoy/Service';
	console.log(URL);
	//注销登录时处理状态
	const mainStore = useMainStore();
	let request:RequestOptions = {
		url: URL, //处
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				...req, //由vue文件传值，
			},
			MethodName: "MBMLogOut",
		},
	}
	service.request(request, (res) => {
		mainStore.logout();
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}
// 检查更新
const GetAppLastVesion = (req, resSuccess, resFail) => {
	var System = uni.getSystemInfoSync();
	const CUSTOMEROBJECT = getStorageSync("CUSTOMEROBJECT")
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
			.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +'/Enjoy/Service';
	let request = {
		url: URL,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: System.platform,
			MethodName: "GetAppLastVesion",
		},
	}
	service.request(request, (res) => {
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}
// 消息注册
const OperatePushReg = (req: IRequestData, resSuccess: (data: IResponseData) => void, resFail: (error: any) => void) => {
	const CUSTOMEROBJECT = getStorageSync("CUSTOMEROBJECT")
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
			.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +'/Enjoy/Service';
	let request = {
		url: URL,
		data: {
			UniqueKey: "管易通40推送消息",
			ObjectData: {
				...req, //由vue文件传值，
			},
			MethodName: "OperateMiPushId",
		},
	}
	service.request(request, (res) => {
		// console.log(res)
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}

interface enjoyServiceIp {
	EnjoyMain?: string;
	EnjoyCRM?: string;
	EnjoyRDS?: string;
	EnjoyBCM?: string;
	EnjoyMall?: string;
	EnjoyOA?: string;
	EnjoyRMIS?: string;
}
// MARK: - 设置EnjoyServiceIp地址
const setEnjoyServiceIp = (resSuccess: SuccessCallback): void => {
	const customerObject = service.getStorageSync("CUSTOMEROBJECT");
	if (customerObject) {
		let enjoyServiceIp:enjoyServiceIp = {};
		const url = (obj: any): string => {
			return (obj.c_mobile_service_ip.indexOf('http') >= 0 ? '' : obj.c_request_http_type + '://') + obj
				.c_mobile_service_ip + '/Enjoy/Service';
		}
		if (customerObject.EnjoyMain) {
			enjoyServiceIp.EnjoyMain = url(customerObject.EnjoyMain);
		}
		if (customerObject.EnjoyCRM) {
			enjoyServiceIp.EnjoyCRM = url(customerObject.EnjoyCRM);
		}
		if (customerObject.EnjoyRDS) {
			enjoyServiceIp.EnjoyRDS = url(customerObject.EnjoyRDS);
		}
		if (customerObject.EnjoyBCM) {
			enjoyServiceIp.EnjoyBCM = url(customerObject.EnjoyBCM);
		}
		if (customerObject.EnjoyMall) {
			enjoyServiceIp.EnjoyMall = url(customerObject.EnjoyMall);
		}
		if (customerObject.EnjoyOA) {
			enjoyServiceIp.EnjoyOA = url(customerObject.EnjoyOA);
		}
		if (customerObject.EnjoyRMIS) {
			enjoyServiceIp.EnjoyRMIS = url(customerObject.EnjoyRMIS);
		}
		if (resSuccess && enjoyServiceIp) {
			resSuccess(enjoyServiceIp);
		}
		// this.enjoyServiceIpin(enjoyServiceIp);
	}
}

interface CUSTOMEROBJECT {
	EnjoyMain: {
	  c_mobile_service_ip?: string;
	  c_request_http_type?: string;
	  [key: string]: any;
	};
  }
interface RequestOptions {
	url: string;
	data: IRequestData;
}
// 定义响应成功和失败的函数类型
type SuccessCallback = (data: any) => void;
type FailCallback = (error: string) => void;

const GetSyscfgByLogin = (req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	const CUSTOMEROBJECT: CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	const reqUrl = `${CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.startsWith('http') 
		? '' 
		: CUSTOMEROBJECT.EnjoyMain.c_request_http_type + '://'}${CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip}/Enjoy/Service`;

	if (reqUrl) {
		const request: RequestOptions = {
			url: reqUrl,
			data: {
			  UniqueKey: "管易通40公共",
			  ObjectData: {
				whereList: [
				  {
					c_type_name: '',
					c_col: 'c_name',
					c_oper: '=',
					c_value: "管e通登录时是否开启验证码功能",
					c_col_dtype: "System.String",
					c_logic: "或者",
				  },
				  {
					c_type_name: '',
					c_col: 'c_name',
					c_oper: '=',
					c_value: "管e通登录时连续失败N次后需要验证码",
					c_col_dtype: "System.String",
					c_logic: "或者",
				  }
				]
			  },
			  MethodName: "GetSyscfg",
			},
		}
		service.request(request, (res) => {
			if (resSuccess && res && res.data) {
			  resSuccess(res.data);
			}
		}, resFail);
	} else {
		resFail('（接口：GetSyscfg）未正确获取到服务器地址！');
	}
}

const GetSyscfgOfTask = (req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	const rdsUrl = getRdsUrl();
	const request: RequestOptions = {
		url: rdsUrl.mainApi,
		data: {
			UniqueKey: "系统配置维护",
			ObjectData: {
				whereList: [
					{ c_col: "c_class", c_oper: "等于", c_value: '任务管理', c_logic: "而且", c_col_dtype: "System.String" }
				]
			},
			MethodName: "EnjoyQueryList",
		},
	}
	service.request(request, (res) => {
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}

const CheckIsInsertCode = (req: any, resSuccess: SuccessCallback, resFail: FailCallback)=> {
	const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
			.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +
		'/Enjoy/Service';
	let request = {
		url: URL, //处
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: req,
			MethodName: "CheckIsInsertCode",
		},
	}
	service.request(request, (res) => {
		if (resSuccess && res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}

const GetSyscfgGoodsLength = (req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	let request:RequestOptions = {
		url: req.EnjoyRMIS,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				IsNotPage: false,
				whereList: [{
					c_type_name: '',
					c_col: 'c_name',
					c_oper: '=',
					c_value: '管e通输入商品可自动检索的字符长度',
					c_col_dtype: "System.String",
					c_logic: "或者",
				}]
			},
			MethodName: "GetSyscfg",
		},
	}
	service.request(request, (res) => {
		if (res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}

interface IdsTokenOptions {
	UserNo: string;
	sRefreshToken: string;
}
// 刷新认证中心Token
const IdsTokenRefreshCheck = (forceRefresh: boolean) => {
	const mainStore = useMainStore();
	//每次从后台进入前台时刷新一下认证中心Token
	const loginInfo = mainStore.loginInfo;//apps.getStorageSync('$state');
	const curretDt = dateRangUtil.getCurrentCNDt();
	console.log(mainStore.hasLogin , loginInfo.OARefreshToken , loginInfo.tokenExpiresDt,curretDt);
	if(mainStore.hasLogin === true && loginInfo && loginInfo.OARefreshToken && (loginInfo.tokenExpiresDt<curretDt || forceRefresh === true)) {
		const req:IdsTokenOptions = {
			UserNo: loginInfo.sUser,
			sRefreshToken: loginInfo.OARefreshToken
		}
		const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
		let url = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
			.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +
			'/Enjoy/Service';
		let request:RequestOptions = {
			url,
			data: {
				UniqueKey: "管易通40公共",
				ObjectData: {
					...req
				},
				MethodName: "RefreshCenterToken",
			},
		}
		service.request(request, (res) => {
			if (res && res.data) {
				const mainStore = useMainStore();
				const { loginInfo } = mainStore;
				mainStore.loginInfoin({
					...loginInfo,
					idsToken: {...res.data.ObjectData}
				})
				console.log('刷新成功了',res.data.ObjectData);
			}
		}, (err)=>{
			console.log('刷新失败了',JSON.stringify(err));
		});

	}


	// // #ifdef H5
	// URL = URL === 'http://60.208.83.246:8049/mbmv5/Enjoy/Service' ? 'http://localhost:5173/mbmv5/Enjoy/Service': 'http://localhost:5173/Enjoy/Service';
	// // #endif
	/*
	uni.request({
		url: URL,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				...req
			},
			MethodName: "RefreshCenterToken",
		},
		dataType: 'json',
		header: {
			'Content-Type': 'application/json;charset=utf-8', //自定义请求头信息
		},
		method: 'POST',
		timeout: 15000, //超时时间设置为8秒；
		withCredentials: true,
		success: (res) => {
			console.log('IdsTokenRefreshCheck-成功',res);
		},
		fail: function(res) {
			console.log('IdsTokenRefreshCheck-失败');
		}
	}); */
}

// 消息状态改为已读
const ModifyMsgToRead =(req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	let request:IRequest = {
		url: OAURL,
		data: {
			UniqueKey: "管易通40推送消息",
			ObjectData: {
				...req,
			},
			MethodName: "ModifyMsgToRead",
		},
	}
	service.request(request, (res) => {
		if (res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}
// 增加日志
const AddModuleUseLog = (req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	let request:IRequest = {
		url: MainURL,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {
				...req
			},
			MethodName: "AddModuleUseLog",
		},
	}
	service.request(request, (res) => {
		if (res && res.data) {
			resSuccess(res.data);
		}
	}, resFail);
}

// 系统参数 主题 EnjoyOA
const GetSyscfgByTheme = (req: any, resSuccess: SuccessCallback, resFail: FailCallback) => {
	const CUSTOMEROBJECT: CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	const reqUrl = `${CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.startsWith('http') 
		? '' 
		: CUSTOMEROBJECT.EnjoyMain.c_request_http_type + '://'}${CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip}/Enjoy/Service`;

	if (reqUrl) {
		const request: RequestOptions = {
			url: reqUrl,
			data: {
			  UniqueKey: "管易通40公共",
			  ObjectData: {
				whereList: [{
					c_type_name: '',
					c_col: 'c_class',
					c_oper: '=',
					c_value: "管e通v5主题配置",
					c_col_dtype: "System.String",
					c_logic: "或者",
				}, {
					c_type_name: '',
					c_col: 'c_name',
					c_oper: '=',
					c_value: "管e通v5默认主题",
					c_col_dtype: "System.String",
					c_logic: "或者",
				}]
			  },
			  MethodName: "GetSyscfg",
			},
		}
		service.request(request, (res) => {
			if (resSuccess && res && res.data) {
			  resSuccess(res.data);
			}
		}, resFail);
	} else {
		resFail('（接口：GetSyscfg）未正确获取到服务器地址！');
	}
}

// 获取菜单
const FetchAvailablePortalData = () => {
	const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
	let URL = (CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip.indexOf('http') >= 0 ? '' : CUSTOMEROBJECT.EnjoyMain
		.c_request_http_type + '://') + CUSTOMEROBJECT.EnjoyMain.c_mobile_service_ip +'/Enjoy/Service';

	let request:RequestOptions = {
		url: URL,
		data: {
			UniqueKey: "管易通40公共",
			ObjectData: {},
			MethodName: "FetchAvailablePortalData",
		},
	}

	service.request(request, (res1) => {
		if (res1.data?.ObjectData) {
			updateHomePageData(res1.data.ObjectData);
		} else {
			updateHomePageData([]);
		}
	}, (err) => {
		updateHomePageData([]);
	})
}

const updateHomePageData = (objectData) => {
	const moduleDataStore = useModuleDataStore();
	moduleDataStore.setDate(objectData);
};
export default {
	getStorageSync,
	setStorageSync,
	GetCloudCustDef,
	addlocalStorage,
	MobileLoginNew,
	OperatePushReg,
	setEnjoyServiceIp,
	GetSyscfgByLogin,
	GetSyscfgOfTask,
	CheckIsInsertCode,
	GetSyscfgGoodsLength,
	MBMLogOut,
	GetAppLastVesion,
	IdsTokenRefreshCheck,
	ModifyMsgToRead,
	AddModuleUseLog,
	GetSyscfgByTheme,
	updateHomePageData,
	FetchAvailablePortalData
}
